#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <filesystem>
#include "unzip_utils.h"

using namespace std;
namespace fs = filesystem;

int main(int argc, char *argv[]) {
    if (argc != 2) {
        cerr << "Wrong argument!" << endl;
        return EXIT_FAILURE;
    }

    string file_path = argv[1];
    ifstream file(file_path, ios::binary);
    if (!file.is_open()) {
        cerr << "Failed opening file!" << endl;
        return EXIT_FAILURE;
    }

    // Read file to memory
    VecData data((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
    file.close();

    auto it = data.cbegin();

    while (it < data.cend()) {
        // Read metadata of one file
        const unsigned char *ptr = &(*it);
        auto *pfe = reinterpret_cast<const FileEntry *>(ptr);

        it += sizeof(FileEntry);
        string path(it, it + pfe->pathlen);
        it += pfe->pathlen;

        // Create output file and its directory
        string parent_path = get_parent_path(path);
        if (!parent_path.empty())
            fs::create_directories(parent_path);

        ofstream output(path, ios::binary);
        if (!output) {
            cerr << "Failed creating file! Maybe wrong path." << endl;
            return EXIT_FAILURE;
        }

        // Decompress one file
        auto file_end = it + pfe->size;
        VecData decompressed = decompress(it, file_end);
        it = file_end;

        output.write(reinterpret_cast<const char *>(decompressed.data()),
                     static_cast<streamsize>(decompressed.size()));
        output.close();
    }

    cout << "Finished decompressing files." << endl;

    return 0;
}
